<?php

namespace app\enterprise\controller;

use app\enterprise\model\course\CourseLinkWare;
use app\enterprise\model\course\Courseware as CoursewareModel;
use app\enterprise\model\TrainType as TrainTypeModel;
use app\enterprise\model\course\Teacher;
use app\enterprise\service\DataType;
use app\enterprise\model\course\Topic;
use think\exception\ValidateException;
use think\Request;

class Courseware extends Enterprise
{
    public function list(Request $request)
    {
        $page= input('page', 1);
        $limit = input('size', 10);
        $title = input('title', '');
        $ids = input('ids', '');
        $exclude_ids = input('exclude_ids', '');
        $create_type = input('create_type', '');
        $type_ids = input('type_ids', []);
        $userIds = userIds($this->adminId);
        $where = [];

//        $where[] = ['creator_id', 'in', $userIds];
        $where[] = [ 'status','=',1];
//        if (empty($create_type)) {
//            return app('json')->fail('请选择要查询的是平台资源还是我的资源');
//        }
        // 公共资源
        $resource_type = input('resource_type', '');

        $is_index = input('is_index', ''); // 列表数据, 不是添加

        if ( !empty($resource_type) ) {
            // 公共资源 可以查看 平台和公共资源
            if ( $resource_type == 1 ) {

//                if ( empty($is_index) ) {
//                    $where[] = [ 'resource_type','in', '1,2' ]; // add的时候
//                } else {
//                    $where[] = [ 'resource_type','=', $resource_type ]; // 列表数据的时候
//                }

                $where[] = [ 'resource_type','=', $resource_type ];

            } else if( $resource_type == 2 ) {
                $where[] = [ 'resource_type','=', $resource_type ];
            } else if ( $resource_type == 3 ) {
                // 只查我的
                $where[] = ['creator_id', '=', $userIds];
                $where[] = [ 'resource_type','=', $resource_type ];
                // 我的资源, 包含公共的, 平台的, 我的
//                $where[] = [ 'resource_type','in', '1,2,3' ];
            }
        }

        $teacher_ids = [];

        $data = CoursewareModel::order('id', 'desc')
            ->when($ids, function ($query) use ($ids) {
                $query->whereIn('id', $ids);
            })
            ->when($exclude_ids, function ($query) use ($exclude_ids) {
                $query->whereNotIn('id', $exclude_ids);
            })
            ->when(!empty($title), function ($query) use ($title) {
                $query->where('title', 'like', '%' . $title . '%');
            })
//            ->where(function ($query) use ($create_type) {
//                if (empty($create_type)) {
//                    $query->where('company_id', $this->adminId)->whereOr('company_id', 0);
//                } else if ($create_type == 1) {
//                    $query->where('company_id', 0);
//                } else {
//                    $query->where('company_id', $this->adminId);
//                }
//            })
            ->where($where)
            ->where(function ($query) use ($type_ids) {
                if (!empty($type_ids)) {
                    foreach ($type_ids as $typeId) {
                        $query->whereOr('type_ids', 'like', '%,' . $typeId . ',%');
                    }
                }

            })
            ->paginate($limit)
            ->each(function ($item) use (&$teacher_ids) {
                if ($item['type_ids']) {
                    $typeIds = explode(',', $item['type_ids'] ?? '');
                    $types = TrainTypeModel::whereIn('id', $typeIds)
                        ->column('title');
                    $item->type_name = implode(',', $types);
                }

                $item->teacher_name = '';
                if (!empty($item['teacher_id'])) {
                    $teacher_ids[] = $item['teacher_id'];
                }
            });
        if (!empty($teacher_ids)) {
            $teachers = Teacher::whereIn('id', $teacher_ids)
                ->column('username', 'id');
                $data->each(function ($item) use ($teachers) {
                    $item->teacher_name = $teachers[$item['teacher_id']] ?? '';
                });
        }

//        $list = $data->items();
//        // 如果是 我的资源, 需要筛选出来 自己的
//        if ( $resource_type == 3 ) {
//            foreach ($list as $key => &$value) {
//                if ( $value['resource_type'] == 3 && $value['creator_id'] != $this->adminId ) {
//                    unset($list[$key]);
//                }
//            }
//        }

        return app('json')->success([
            'list' => $data->items(),
            'total' => $data->total(),
            'total_page'=>$data->lastPage(),
        ]);
    }

    public function info()
    {
        $id = input('id', '');
        if ($id) {
            $data = CoursewareModel::getOne($id);
            if (!empty($data) && ($data['company_id'] == $this->adminId || $data['company_id'] == 0)) {

                try {
                    $data['selected_type_ids'] = DataType::getTrainTypeRelateIds($data['type_ids']);
                    $data['type_ids'] = explode(',', trim($data['type_ids'], ','));
                } catch (\Exception $e) {
                    $data['type_ids'] = [];
                }

                if (!empty($data['topic_ids'])) {
                    $data['topic_ids'] = json_decode($data['topic_ids'], true);
                }
            }

        } else {
            $data = null;
        }
        $types = DataType::getTrainType();

        return app('json')->success([
            'data' => $data,
            'types' => $types,
        ]);
    }

    public function save(Request $request)
    {

        $data = $request->only([
            'type_ids', 'title', 'duration', 'hour', 'teacher_id', 'video_url', 'img_url',
            'topic_ids', 'create_type', 'topic_open'
        ]);
        try {
            validate([
                'type_ids|培训类型' => 'require|array',
                'title|课件名称' => 'require|max:255',
                'duration|课件时长' => 'require|number',
                'hour|学时' => 'require|number',
                // 'teacher_id|关联教师' => 'require|number',
                'video_url|课件视频' => 'require|max:255',
                'topic_ids|习题' => 'array',
                'create_type|资源所属'=>'require|number|in:1,2',
                'topic_open|是否开启练习题' => 'number|in:1,2'
            ])->check($data);

            if ($data['topic_open'] == 1) {
                if (empty($data['topic_ids'])) {
                    return app('json')->fail('请选择课后习题');
                }
            }

            if ($data['create_type'] == 1) {
                $data['company_id'] = 0;
            } else{
                $data['company_id'] = $this->adminId;
            }
            $id = input('id', '');

            $data['type_ids'] = ','.implode(',', $data['type_ids']).',';
            if (empty($data['topic_ids'])) {
                $data['topic_ids'] = '[]';
            } else {
                $data['topic_ids'] =  json_encode(array_unique($data['topic_ids']));
            }
            if (!$id) {
                // 是否是公共资源
                $resource_type = input('resource_type', '');
                if ( !empty($resource_type)  )  {
                    $data['resource_type'] = $resource_type;
                }
                $data['creator_id'] = $this->adminId;
                $res = CoursewareModel::create($data);
                $id = $res->id;
            } else {
                $one = CoursewareModel::getOne($id);

                if (!$one) {
                    return app('json')->fail('要操作的数据不存在');
                }

                if ($one['company_id'] != $this->adminId) {
                    return app('json')->fail('您没有权限操作该数据');
                }

                $res = CoursewareModel::update($data, ['id' => $id]);
            }
            return app('json')->success();
        } catch (ValidateException $exception) {
            return app('json')->fail($exception->getMessage());
        }

    }

    public function topics()
    {
        $id = input('id', '');

        if (empty($id)) {
            return app('json')->success(['list' => []]);
        }

        $data = CoursewareModel::getOne($id);

        if (empty($data)) {
            return app('json')->success(['list' => []]);
        }

        if (empty($data['topic_ids'])) {
            return app('json')->success(['list' => []]);
        }

        $topic_ids = json_decode($data['topic_ids']);

        if (empty($topic_ids) || !is_array($topic_ids)) {
            return app('json')->success(['list' => []]);
        }

        $topics = Topic::whereIn('id', $topic_ids)->where('status', 1)
            ->orderField('id', $topic_ids)
            ->select()
            ->each(function ($item) {
                if ($item['type_ids']) {
                    $typeIds = explode(',', $item['type_ids'] ?? '');
                    $types = TrainTypeModel::whereIn('id', $typeIds)
                        ->column('title');
                    $item->type_name = implode(',', $types);
                }
            });

        return app('json')->success(['list' => $topics]);



    }

    public function delete(Request $request)
    {
        $id = input('id', '');
        $data = CoursewareModel::getOne($id);
        if (!$id || !$data) {
            return app('json')->fail('要操作的数据不存在');
        }
        if ($data['company_id'] != $this->adminId) {
            return app('json')->fail('您没有权限操作该数据');
        }

        // 查询是否有课程使用了该课件
        $exists = CourseLinkWare::where('courseware_id', $id)
            ->where('status', 1)
            ->count();
        if ($exists) {
            return app('json')->fail('当前课件已使用，不可删除');
        }
        CoursewareModel::dataDelete($id);
        return app('json')->success();
    }
}